﻿#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>
#include <QImage>
#include <QDateTime>
#include <QThread>
#include <QWidgetAction>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    connect(&m_timer,&QTimer::timeout,this,&MainWindow::slotTimeOut);
}

MainWindow::~MainWindow()
{
    qDebug() << "-----------------------------------------------------------------";
    if(m_VideoCapture.isOpened()){
        qDebug() << "00000000000---------------------------------------";
        m_VideoCapture.release();
    }
    delete ui;
}
/*
            QImage                      　 Mat
数据指针 uchar* bits() 　　　　　　　　 uchar* data
宽度　　 int width() 　　　　　　　　　　 int cols
高度 　　 int height() 　　　　　　　　　 int rows
步长　　 int bytesPerLine() 　　　　　　 cols * channels（）
格式　　 Format_Indexed8 　　　　　　 8UC1, GRAY,灰度图
Format_RGB888 　　　　　　　 8UC3, BGR,3通道真彩色 （需要使用cvtColor调换顺序）
Format_ARGB32　　　　　　　8UC4, BGRA，4通道真彩色（需要使用cvtColor调换顺序）
*/
QImage MainWindow::cvMat2QImage(const Mat &mat)
{
    // 8-bits unsigned, NO. OF CHANNELS = 1
    if(mat.type() == CV_8UC1)
    {
//        QImage image(mat.cols, mat.rows, QImage::Format_Indexed8);
//        // Set the color table (used to translate colour indexes to qRgb values)
//        image.setNumColors(256);
//        for(int i = 0; i < 256; i++)
//        {
//            image.setColor(i, qRgb(i, i, i));
//        }
//        // Copy input Mat
//        uchar *pSrc = mat.data;
//        for(int row = 0; row < mat.rows; row ++)
//        {
//            uchar *pDest = image.scanLine(row);
//            memcpy(pDest, pSrc, mat.cols);
//            pSrc += mat.step;
//        }
//        return image;
    }
    // 8-bits unsigned, NO. OF CHANNELS = 3
    else if(mat.type() == CV_8UC3)
    {
        //cur test---------------------------------------------------------------mat.type=16
        // Copy input Mat
        const uchar *pSrc = (const uchar*)mat.data;
        // Create QImage with same dimensions as input Mat
        QImage image(pSrc, mat.cols, mat.rows, mat.step, QImage::Format_RGB888);
        return image.rgbSwapped();
    }
    else if(mat.type() == CV_8UC4)
    {
        // Copy input Mat
        const uchar *pSrc = (const uchar*)mat.data;
        // Create QImage with same dimensions as input Mat
        QImage image(pSrc, mat.cols, mat.rows, mat.step, QImage::Format_ARGB32);
        return image.copy();
    }
    else
    {
        return QImage();
    }
    return QImage();
}
static qint64 s_nTime = 0;
static int s_nFrameRate = 0;
bool MainWindow::GetcvMatFrame(Mat &mat)
{
    bool bResult = false;
    qint64 tmptime = QDateTime::currentMSecsSinceEpoch();
    bResult = m_VideoCapture.read(mat);
    qDebug() << "cv read interval=" << QDateTime::currentMSecsSinceEpoch() - tmptime;

    if((QDateTime::currentDateTime().toTime_t() - s_nTime) < 1)
    {
        s_nFrameRate++;
    }
    else
    {
        qDebug() << u8"1s内多少帧=" << s_nFrameRate;
        s_nTime = QDateTime::currentDateTime().toTime_t();
        s_nFrameRate = 0;
    }

    return bResult;
}

void MainWindow::slotTimeOut()
{
    Mat mat;
    if(GetcvMatFrame(mat)){
        QImage img = cvMat2QImage(mat);
        ui->label->setPixmap(QPixmap::fromImage(img.scaled(ui->label->size())));
    }else{
        qDebug() << u8"读取空图像";
    }
}

void MainWindow::on_btnOpenCamera_clicked()
{
    ////opencv camera
    qDebug() << "open camera result=" << m_VideoCapture.open(0);
    if(m_VideoCapture.isOpened()){
        m_VideoCapture.set(CAP_PROP_FOURCC, VideoWriter::fourcc('M', 'J', 'P', 'G'));
//        m_VideoCapture.set(CAP_PROP_FRAME_WIDTH, 3264);
//        m_VideoCapture.set(CAP_PROP_FRAME_HEIGHT,2488);
        m_VideoCapture.set(CAP_PROP_FRAME_WIDTH, 1600);
        m_VideoCapture.set(CAP_PROP_FRAME_HEIGHT,1200);
        qDebug() << m_VideoCapture.get(CAP_PROP_FRAME_WIDTH) << m_VideoCapture.get(CAP_PROP_FRAME_HEIGHT) << m_VideoCapture.get(CAP_PROP_FPS);
    }
}

void MainWindow::on_btnGetFrameShow_clicked()
{
    //获取一帧显示
    Mat mat;
    if(GetcvMatFrame(mat)){
        QImage img = cvMat2QImage(mat);
        ui->label->setPixmap(QPixmap::fromImage(img.scaled(ui->label->size())));
    }else{
        qDebug() << u8"读取空图像";
    }
}

void MainWindow::on_btnAlwaysShow_clicked()
{
//    m_timer.start(40);
//    return;
    m_bInterupt = true;
    while(1){
        if(m_bInterupt){
            Mat mat;
            if(GetcvMatFrame(mat)){
                QImage img = cvMat2QImage(mat);
                ui->label->setPixmap(QPixmap::fromImage(img.scaled(ui->label->size())));
                QCoreApplication::processEvents(QEventLoop::AllEvents,5);
            }else{
                qDebug() << u8"读取空图像";
            }
        }else{
            break;
        }
    }
}

void MainWindow::on_btnStopAlwaysShow_clicked()
{
    m_bInterupt = false;
}
#include <QFile>
#include <QJsonParseError>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
void MainWindow::on_pushButton_clicked()
{
    QFile file("1.json");
    if(!file.open(QIODevice::ReadOnly)){
        return;
    }
    QByteArray JsonData = file.readAll();
    QJsonParseError error;
    QJsonDocument doc = QJsonDocument::fromJson(JsonData, &error);
    if(QJsonParseError::NoError != error.error){
        qDebug() << "Common::ImageDrawRect QJsonParseError";
        return;
    }
    QJsonObject obj = doc.object();
    QJsonArray array = obj.value("data").toArray();
    QJsonObject foodone;
    foodone.insert("id",200);
    foodone.insert("x1",200);
    foodone.insert("x2",200);
    foodone.insert("y1",200);
    foodone.insert("y2",200);
    array.push_back(QJsonValue(foodone));

    obj.insert("data", QJsonValue(array));

    QJsonDocument saveDoc;
    saveDoc.setObject(obj);
    qDebug() << saveDoc.toJson().data();
}
